class User < ActiveRecord::Base
  include ActiveModel::Validations

  class UniquenessEnterpriseValidator < ActiveModel::EachValidator
    def validate_each(record, attribute, value)
      record.errors[attribute] << "已注册" if value.nil?
    end
  end
  
  has_secure_password
  
  validates :enterprise_id,
    :uniqueness_enterprise => true
  validates :full_name,
    :mobile,
    :presence => true  
  validates :email, 
    :format => {
      :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
    }
  validates :mobile,
    :uniqueness  => {
      :scope =>  :enterprise_id    
    }
  validates :email,
    :uniqueness  => {
      :scope =>  :enterprise_id    
    }

  attr_protected :pk,
    :login_token,
    :status

  attr_protected [], :as => :admin
    
  belongs_to :enterprise
  has_and_belongs_to_many :groups, :uniq => true

  default_scope lambda { order('position asc') }

  scope :current_enterprise, lambda { 
    where( :enterprise_id => Enterprise.current_id )
  }
  scope :active, lambda { where(:status => 'active').current_enterprise }
  scope :disable, lambda { where(:status => 'disable').current_enterprise }
  scope :active_or_locked, lambda { where('status in (?)',['active','locked']).current_enterprise }
  scope :workmates, lambda { where(:enterprise_id => User.current.enterprise).current_enterprise }
  scope :by_group_name, lambda { | group_name | where( 'id in (?)', Group.where(:name => group_name).first.users.collect {|user| user.id } ) }
  
  before_create do |user|
    user.pk = ::SecureRandom.hex(32)
  end

  def reset_login_token!
    self.login_token = ::SecureRandom.hex(32)
    save(:validate => false)
  end  

  def is_admin?
    enterprise.admin == self or groups.any? {|group| group.admin? }
  end
  
  def self.current
    Thread.current[:current_user_id] ? find(Thread.current[:current_user_id]) : nil
  end
  
  def self.current_id 
    Thread.current[:current_user_id]
  end
  
  # 当前登录人？
  def current?
    id == User.current.try(:id)
  end
  
  def self.has_loggined?
    current
  end
    
  def self.authenticate(args = {})    
    where(
      'enterprises.name = :enterprise_name and users.mobile = :mobile', 
      args
    ).includes(:enterprise).first.try(:authenticate, args[:password])
  end
  
  # 安全key存储在cookies
  def security_key_in_cookies
    Digest::SHA1.hexdigest(id.to_s + pk)
  end

  def check_security_key_in_cookies(sk)
    security_key_in_cookies == sk
  end

  def reset_password
    self.password = '1234'
  end
  
  def reset_password!
    reset_password
    save(:validate => false)
  end
    
  def status
    ActiveSupport::StringInquirer.new(self[:status])
  end

  def feed_view_type
    ActiveSupport::StringInquirer.new(self[:feed_view_type])
  end
  
  def locked!
    status! 'locked'
  end

  def disabled!
    status! 'disabled'
  end
  
  def active!
    status! 'active'
  end
  
  def status!(new_status)
    self.status = new_status
    save(:validate => false)
  end

  def nick_name
    id == User.current_id ?  '我' : full_name
  end

  def position!(new_position)
    self.position = new_position
    self.save(:validate => false)
  end

  def me?
    User.current == self
  end

  def full_name_with_mobile
    "#{full_name} ☏:#{mobile}"
  end
    
end
